package model

import "gorm.io/gorm"

type Follow struct {
	FollowerID int            `gorm:"not null"`
	FocusID    int            `gorm:"not null"`
	DeletedAt  gorm.DeletedAt `gorm:"index"`
	User1      *User          `gorm:"foreignKey:FollowerID"`
	User2      *User          `gorm:"foreignKey:FocusID"`
}

type FollowMini struct {
	FocusID int `json:"FocusID"`
}

func IfFollowed(follow int, focus int) (bool, error) {
	var count int64
	result := DB.Model(&Follow{}).Where("FollowerID=? and FocusID=?", follow, focus).Count(&count)
	if result.Error != nil {
		return false, result.Error
	}
	if count == 0 {
		return false, nil
	} else {
		return true, nil
	}
}

func GetFocusIDList(uid int) ([]FollowMini, error) {
	var focusList []FollowMini
	err := DB.Model(&Follow{}).Where("FollowerID = ?", uid).Find(&focusList).Error
	return focusList, err
}

func AddFocus(follow int, focus int) error {
	ff := Follow{
		FollowerID: follow,
		FocusID:    focus,
	}
	err := DB.Model(&Follow{}).Create(&ff).Error
	if err != nil {
		return err
	}
	err = DB.Model(&User{}).Where("UserID = ?", focus).UpdateColumn("FansNum", gorm.Expr("FansNum + ?", 1)).Error
	if err != nil {
		return err
	}
	err = DB.Model(&User{}).Where("UserID = ?", follow).UpdateColumn("IdolNum", gorm.Expr("IdolNum + ?", 1)).Error
	return err
}

func DeleteFocus(follow int, focus int) error {
	err := DB.Where("FollowerID = ? and FocusID = ?", follow, focus).Delete(&Follow{}).Error
	if err != nil {
		return err
	}
	err = DB.Model(&User{}).Where("UserID = ?", focus).UpdateColumn("FansNum", gorm.Expr("FansNum - ?", 1)).Error
	if err != nil {
		return err
	}
	err = DB.Model(&User{}).Where("UserID = ?", follow).UpdateColumn("IdolNum", gorm.Expr("IdolNum - ?", 1)).Error
	return err
}
